'use client';

import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';

export default function VisitTracker() {
  const pathname = usePathname();
  const prevPathRef = useRef<string | null>(null);
  const visitRecordedRef = useRef<boolean>(false);

  useEffect(() => {
    // 确保代码只在浏览器环境中执行
    if (typeof window === 'undefined') return;

    // 如果是初始加载和首次渲染，记录一次访问
    if (!prevPathRef.current) {
      prevPathRef.current = pathname;
      
      // 页面完全加载后记录访问
      if (document.readyState === 'complete') {
        recordVisit();
      } else {
        window.addEventListener('load', recordVisit, { once: true });
        return () => window.removeEventListener('load', recordVisit);
      }
    } 
    // 路径变化时记录访问
    else if (prevPathRef.current !== pathname) {
      prevPathRef.current = pathname;
      visitRecordedRef.current = false;
      recordVisit();
    }
  }, [pathname]);
  
  // 记录访问的函数
  const recordVisit = async () => {
    // 确保代码只在浏览器环境中执行
    if (typeof window === 'undefined') return;
    
    // 避免重复记录
    if (visitRecordedRef.current) return;
    visitRecordedRef.current = true;
    
    try {
      // 直接发送路径到API，让服务端从cookie中获取会话ID
      await fetch('/api/session/visit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ path: pathname }),
        // 确保发送cookie到服务端
        credentials: 'same-origin'
      });
    } catch (error) {
      console.error('记录访问失败:', error);
    }
  };
  
  return null; // 不渲染任何内容
} 